// 完成 
const path = require('path');
const db = require(path.join(__dirname, '../utils', 'db'));
const utility = require('utility');
const express = require('express');
const router = express.Router();

// router.get('xxx', async (req, res) => {

// });
// router.get('/test', async (req, res) => {
//     res.send('hahaha，我是需要token才能访问的接口，我的名字是：' + req.user.username);
// });

// 获取用户信息
router.get('/userinfo', async (req, res) => {
    let r = await db('select * from user where username=?', req.user.username);
    // console.log(r);
    if (r && r.length > 0) {
        delete r[0].password;
        res.json({
            status: 0,
            message: '获取用户基本信息成功',
            data: r[0]
        });
    } else {
        res.json({
            status: 1,
            message: '获取用户信息失败'
        });
    }
});

// 更新用户信息
router.post('/userinfo', async (req, res) => {
    let obj = {
        nickname: req.body.nickname,
        email: req.body.email
    }
    let r = await db('update user set ? where id=?', [obj, req.body.id]);
    if (r && r.affectedRows > 0) {
        res.json({
            status: 0,
            message: '修改用户信息成功！'
        });
    } else {
        res.json({
            status: 1,
            message: '修改用户信息失败！'
        });
    }
});

// 重置密码
router.post('/updatepwd', async (req, res) => {
    // 判断两次密码是否一致
    if (req.body.oldPwd === req.body.newPwd) {
        return res.json({
            status: 1,
            message: '新密码不能和原密码相同'
        });
    }
    // 先根据用户名和原来的密码查询。如果查询到信息，说明原密码正确，是本人操作
    let a = await db('select * from user where username=? and password=?', [req.user.username, utility.md5(req.body.oldPwd)]);
    if (a === undefined || a.length === 0) {
        // 说明没有查到信息，说明原密码不对，不是本人操作
        return res.json({
            status: 1,
            message: '原密码不对'
        });
    }
    // 原密码正确，而且新密码和原密码也不一样，下面进行更新操作
    let arr = [
        utility.md5(req.body.newPwd), 
        req.user.username
    ];
    let r = await db('update user set password=? where username=?', arr);
    if (r && r.affectedRows > 0) {
        res.json({
            status: 0,
            message: '更新密码成功'
        });
    } else {
        res.json({
            status: 1,
            message: '更新密码失败'
        });
    }
});

// 更换头像
router.post('/update/avatar', async (req, res) => {
    let arr = [
        req.body.avatar,
        req.user.username
    ];
    let r = await db('update user set user_pic=? where username=?', arr);
    if (r && r.affectedRows > 0) {
        res.json({
            status: 0,
            message: '更新头像成功'
        });
    } else {
        res.json({
            status: 1,
            message: '更新头像失败'
        });
    }
});



module.exports = router;